package com.meta.builder.schema;

import com.meta.internal.Options;
import com.sun.codemodel.CodeWriter;
import com.sun.codemodel.JPackage;

import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

public class MeteCodeWriter extends CodeWriter {

    private final Options options;
    private  PrintStream out;

    /**
     * @param
     */
    public MeteCodeWriter(Options options) {
        this.options = options;
    }

    @Override
    public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
        String pkgName = pkg.name();
        options.getProcessingEnv().getMessager().printMessage(Diagnostic.Kind.WARNING, "======doing pkgName: " + pkg.name());
        options.getProcessingEnv().getMessager().printMessage(Diagnostic.Kind.WARNING, "======doing pkg: " + fileName);
        JavaFileObject fileObject = options.getProcessingEnv().getFiler().createSourceFile(pkg.name() + "." + fileName.replaceAll(".java", ""));
        if (out != null) {
            this.close();
        }
        OutputStream outputStream = fileObject.openOutputStream();
        this.out = new PrintStream(outputStream);
        if (pkgName.length() != 0) pkgName += '.';
        return new FilterOutputStream(out) {
            public void close() {
                // don't let this stream close
            }
        };
    }

    @Override
    public void close() throws IOException {
        out.flush();
        out.close();
    }
}

